package service.outputDocument;

import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class WordWriter {
    private Map titleMap;
    private Map paragraphMap;
    private File file;
    WordWriter(List<Map> content, File file) {
        this.file=file;
        titleMap = new TreeMap();
        paragraphMap = new TreeMap();
        if (content.size()==2){
            this.titleMap.putAll(content.get(0));
            this.paragraphMap.putAll(content.get(1));
        }else {
            titleMap=null;
            paragraphMap.putAll(content.get(0));
        }
    }

    void creatWord() throws IOException {
        //
        XWPFDocument document = new XWPFDocument();
        if (titleMap!=null){
            XWPFParagraph mainTitle = document.createParagraph();
            XWPFRun run = mainTitle.createRun();
            mainTitle.setAlignment(ParagraphAlignment.CENTER);
            run.setText(titleMap.get(0).toString());
            if (titleMap.size()<20){
                run.setBold(true);
            }
            run.setFontSize(20);
        }
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setFontSize(14);
        for (int i =0;i<paragraphMap.size();i++){
            run.addTab();
            run.setText(paragraphMap.get(i).toString());
            run.addCarriageReturn();
        }
        //在文件系统中输出文档
        FileOutputStream out = new FileOutputStream(file);
        document.write(out);
        out.close();
        document.close();
        System.out.println("a.docx written successfully"+file);

    }
}
